var uuidV4 = require('uuid/v4');
var Eventproxy = require('eventproxy');
var logger = require('../common/logger');
var models = require('../models');
var tools = require('../common/tools');
var config = require('config-lite');

exports.newArea = function newArea(req, res, next) {
  var ep = new Eventproxy();
  ep.fail(next);

  var user = req.user;
  var data = req.body;

  var areaId = req.params.uuid;

  ep.all('missing', function (attrs) {
    if (attrs.length) {
      return res.send_data({
        code: 400,
        message: '缺少字段' + attrs
      });
    }
  });
  var missingAttrs = tools.checkMissingAttr(data, ['name', 'name_en', 'code', 'type']);
  if (missingAttrs.length) {
    return ep.emit('missing', missingAttrs);
  }

  data.code += '';

  data.name = data.name.trim();
  data.name_en = data.name_en.trim();
  data.code = data.code.trim();

  data.event_uuid = user.event_uuid;

  if (areaId) { // 编辑
    models.area.update(data, {
      where: {
        uuid: areaId
      }
    }).then(function() {
      return res.send_data();
    });
  } else {
    models.area.create(data).then(function() {
      return res.send_data();
    });
  }
};

exports.getAreas = function getAreas(req, res, next) {
  var reqQuery = req.query;
  var page = parseInt(reqQuery.page, 10) || 1;
  page = page > 0 ? page : 1;
  var limit = models.user.pageLimit(Number(reqQuery.limit));
  var offset = models.user.pageOffset(page, limit);

  var type = reqQuery.type || 'all';

  var condition = {
    offset: offset,
    limit: limit,
    where: {},
    include: [{
      as: 'belongto_area',
      model: models.area
    }]
  };

  if (type !== 'all') {
    condition.where = {
      type: type
    };
  }

  var user = req.user;
  if (user.event_uuid) {
    condition.where.event_uuid = user.event_uuid;
  }

  models.area.findAndCountAll(condition).then(function(returnAreas) {
    return res.send_data({
      entities: returnAreas.rows,
      total_pages: models.area.totalPages(returnAreas.count, limit),
      current_page: page
    })
  });
};

exports.getAreaByUUID = function getAreaByUUID(req, res) {
  var areaUUID = req.params.uuid;

  models.area.findOne({
    where: {
      uuid: areaUUID
    }
  }).then(function(returnArea) {
    return res.send_data({
      entities: returnArea
    });
  });
};

exports.delArea = function delArea(req, res) {
  var data = req.body;

  var areaId = req.params.uuid;

  models.area.destroy({
    where: {
      uuid: areaId
    }
  }).then(function() {
    return res.send_data();
  });

  models.position_area.destroy({
    where: {
      area_uuid: areaId
    }
  }).then(function() {
    logger.info('Area: ' + areaId + ' 相关的position_areas信息已删除！');
  });

  models.group_area.destroy({
    where: {
      area_uuid: areaId
    }
  }).then(function() {
    logger.info('Area: ' + areaId + ' 相关的group_areas信息已删除！');
  });
};
